//
//  JWWebService.m
//  JWBrowser
//
//  Created by Dejun Liu on 14-12-10.
//  Copyright (c) 2014年 JW. All rights reserved.
//

#import "JWWebService.h"

@implementation JWWebService

JW_SINGLETON_IMPL(JWWebService)

- (instancetype)init
{
    self = [super init];
    if (self) {
        _comunicator = [[JWSingleSite alloc] init];
        _baseURL = [NSURL URLWithString:[AppSettingManager sharedInstance].baseURL];
    }
    return self;
}

- (void)getWithParams:(NSDictionary *)dic jsonResponse:(Complation ) complation
{
//    dic = [self readyParams:dic];
    [self.comunicator GetURLString:_baseURL.absoluteString params:dic jsonResponse:^(id responseData, NSError *error) {
        if (responseData) {
            NSData *data = responseData;
//            DLogLine(@"%@",[[NSString alloc] initWithData:data encoding:4]);
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            responseData = dic;
        }
        complation(responseData,error);
    }];
}
- (void)postWithParams:(NSMutableDictionary *)dic jsonResponse:(Complation) complation
{
    dic = [self readyParams:dic];
    [self.comunicator PostURLString:_baseURL.absoluteString params:dic jsonResponse:^(id responseData, NSError *error) {
        complation(responseData,error);
    }];
}

- (NSMutableDictionary *)readyParams:(NSMutableDictionary *)dic
{
    if ([dic objectForKey:@"params"]) {
        NSError *error;
        NSData *paramJsonData = [NSJSONSerialization dataWithJSONObject:[dic objectForKey:@"params"] options:NSJSONWritingPrettyPrinted error:&error];
        if(error) DLogLine(@"上传JSON错误：%@",error);
        NSString *pramasJsonString = [[NSString alloc] initWithData:paramJsonData encoding:4];
        [dic setObject:pramasJsonString forKey:@"params"];
        return dic;
    }else
    {
        return dic;
    }
}

- (void)postWithAction:(NSString *)action params:(NSMutableDictionary *)dic jsonResponse:(JWComplation) complation
{
    NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
    [postDic hs_setSafeValue:action forKey:@"action"];
    [postDic hs_setSafeValue:dic forKey:@"params"];
    DLogLine(@"url:%@ \r\nparams:%@",self.baseURL.absoluteString,postDic);
    [self postWithParams:postDic jsonResponse:^(id responseData, NSError *error) {
        if (responseData) {
            NSData *data = responseData;
            DLogLine(@"%@",[[NSString alloc] initWithData:data encoding:4]);
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            responseData = dic;
        }
        complation(responseData,error);
    }];
}

@end
